<template>
  <div class="m-table-operation-wrap" :class="isPagination ? 'm-pagination' : ''">
    <el-row style="margin-bottom: 10px">
      <el-col :span="4" :offset="20" class="text-right">
        <el-button type="default" :icon="downloadIcon" @click.stop="tableDownloadHandle" />
        <el-button type="default" :icon="filterIcon" @click.stop="checkTableColumnShowHandle" />
      </el-col>

      <el-card class="m-check-card" v-if="checkTableColumnShow" @click.stop>
        <el-checkbox-group v-model="checkTableColumn" class="m-check-group-wrap">
          <el-checkbox v-for="item in tableColumn" :key="item" :label="item">
            {{ item }}
          </el-checkbox>
        </el-checkbox-group>
      </el-card>
    </el-row>
    <slot :ctc="checkTableColumn"></slot>
  </div>
</template>

<script lang="ts" setup>
import { useIcon } from '@/hooks/useIcon';
// import { jsontoexcel } from "vue-table-to-excel";
import colunmMap from '@/utils/mDownloadTxtMap';
import { isArray } from '@/utils/util';
import { useRoute } from 'vue-router';
import * as XLSX from 'xlsx';

const myRoute = useRoute();

const downloadIcon = useIcon({ name: 'el-icon-download' });
const filterIcon = useIcon({ name: 'el-icon-filter' });

const props = defineProps({
  isPagination: {
    type: Boolean,
    default: true
  },
  tableColumn: {
    type: Array,
    default: []
  },
  tableData: {
    type: Array,
    default: []
  }
});

const checkTableColumnShow = ref(false);

const checkTableColumnShowHandle = () => {
  checkTableColumnShow.value = !checkTableColumnShow.value;
};

const checkTableColumn = ref([]);

onMounted(() => {
  checkTableColumn.value = props.tableColumn;

  document.onclick = function () {
    checkTableColumnShow.value = false;
  };
});

const tableDownloadHandle = () => {
  // const item = [
  //     { '테이블명': 'PP회원ID', },
  //     { '테이블명': 'PP회원ID', },
  //     { '테이블명': 'PP회원ID', },
  // ]

  // console.log(XLSX);

  // const data1 = XLSX.utils.json_to_sheet(item)
  // const wb = XLSX.utils.book_new()
  // XLSX.utils.book_append_sheet(wb, data1, '333333')
  // XLSX.writeFile(wb, 'aa.xlsx')

  // return;

  const myRoutePath = myRoute.path
    .split('/')
    .filter((item) => item)
    .join('-');

  const head = props.tableColumn.slice(0);
  const data = props.tableData.slice(0);

  const itemValueGet = (item, key) => {
    if (!isArray(key)) {
      return item[key];
    }
    for (let i = 0; i < key.length; i++) {
      if (item[key[i]] !== undefined) {
        return item[key[i]] || '';
      }
    }
  };

  const dataDecorate = data.map((item: any) => {
    let _item = {};
    head.map((headItem: any) => {
      const key = colunmMap[headItem];
      _item[headItem] = itemValueGet(item, key);
    });
    return _item;
  });

  const fileName = `${myRoutePath}.xls`;
  const dataSheet = XLSX.utils.json_to_sheet(dataDecorate);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, dataSheet, 'jadeSoft-Agent');
  XLSX.writeFile(wb, fileName);

  // console.log(data)
  // console.log(head)
  // console.log(dataDecorate)

  // return;

  // const fileName = 'JadeSoft-Agent-download.xlsx'
  // const fileName = 'JadeSoft-Agent-download.cvs'
  // const fileName = `${myRoutePath}.cvs`;
  // const fileName = `${myRoutePath}.xlsx`;
  // const fileName = `${myRoutePath}.xls`;

  // jsontoexcel.getXlsx(dataDecorate, head, fileName);
  // getXlsx(dataDecorate, head, fileName);
};

const getXlsx = (jsonData, header, name) => {
  let str = header.toString() + '\n';
  for (let i = 0; i < jsonData.length; i++) {
    for (let item in jsonData[i]) {
      str += `${jsonData[i][item]},`;
    }
    str += '\n';
  }
  // let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)/
  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
  // let uri = 'data:text/csv;charset=unicode,\ufeff' + encodeURIComponent(str)
  var link = document.createElement('a');
  link.href = uri;
  link.download = name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style lang="scss" scoped>
.m-check-card {
  z-index: 9;
  position: absolute;
  top: 42px;
  right: 0;
}

.m-check-card .el-card__body {
  height: 500px;
  overflow: auto;
}

.m-check-group-wrap {
  display: flex;
  flex-direction: column;
}
</style>
